package com.innovation.sys.common.utils;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.innovation.sys.common.constant.SourceParam;
import com.innovation.sys.common.singleton.ChannelSftpSingleton;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.SftpProgressMonitor;

public class SFTPUploaderUtils {

	private static Logger logger = LoggerFactory.getLogger(SFTPUploaderUtils.class);

	private SFTPUploaderUtils() {
	}

	public static void uploadFilesToServer(String srcPath, String dst, SftpProgressMonitor monitor) throws Exception {
		ChannelSftp sftp = upload(srcPath, dst, monitor);
		if (sftp != null) {
			sftp.quit();
			sftp.disconnect();
			logger.info(" SFTP disconnected successfully!");
		}
		ChannelSftpSingleton.getInstance().closeChannel();
	}

	private static ChannelSftp upload(String path, String dst, SftpProgressMonitor monitor) throws SftpException {
		File file = new File(path);
		if (!file.exists()) {
			return null;
		}
		ChannelSftp chSftp = null;
		try {
			chSftp = ChannelSftpSingleton.getInstance().getChannelSftp();
		} catch (JSchException e) {
			logger.info("An Exception has occured when it connecting the SFTP Server!", e);
		}
		if (chSftp == null) {
			return null;
		}
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			if (files == null || files.length <= 0) {
				return null;
			}
			for (File f : files) {
				String fp = f.getAbsolutePath();
				if (f.isDirectory()) {
					String mkdir = dst + "/" + f.getName();
					try {
						chSftp.cd(mkdir);
					} catch (Exception e) {
						logger.info("the given directory isn't exist!creating it.", e);
						chSftp.mkdir(mkdir);
					}
					upload(fp, mkdir, monitor);
				} else {
					chSftp.put(fp, dst, monitor, ChannelSftp.OVERWRITE);
				}
			}
		} else {
			String fp = file.getAbsolutePath();
			chSftp.put(fp, dst, monitor, ChannelSftp.OVERWRITE);
		}
		return chSftp;
	}

	public static void main(String[] args) {
		try {
			uploadFilesToServer(SourceParam.EXPORT_PATH, SourceParam.UPLOAD_PATH, new SftpProgressMonitor() {
				@Override
				public void init(int i, String src, String dst, long size) {
					logger.info("uploading " + src + " to " + dst + "，files size：" + (double) (size / 1024) + "kb");
				}

				@Override
				public boolean count(long l) {
					return true;
				}

				@Override
				public void end() {
					logger.info("uploaded successfully!");
				}
			});
		} catch (Exception e) {
			logger.info("uploaded unsuccessfully!", e);
		}
	}
}
